package hw;

import java.io.File;
import java.util.ArrayList;

public class FileChangesBroadcasterThread extends Thread {
	private final ArrayList<FileChangesListener> listeners = new ArrayList<FileChangesListener>();
	private final ArrayList<FileChangesWatcher> filesWatchers = new ArrayList<FileChangesWatcher>();
	private final int period;
	private boolean stopped = false;
	public FileChangesBroadcasterThread(final int period) {
		super("FileChangesBroadcasterThread");
		this.period = period;
	}
	
	@Override
	public void run() {
		while (!stopped ) {
			for (final FileChangesWatcher fw : filesWatchers) {
				if (fw.hasChanged())
					fireFileChange(fw.getFile());
			}
			try {
				Thread.sleep(period*1000);
			} catch (final InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	private void fireFileChange(final File file) {
		for (final FileChangesListener fcl : listeners)
			fcl.onChange(file);
	}
	public void addWatcher(final FileChangesWatcher watcher) {
		filesWatchers.add(watcher);
	}
	public void register(final FileChangesListener listener) {
		listeners.add(listener);
	}
	public void removeWatcher(final FileChangesWatcher watcher) {
		filesWatchers.remove(watcher);
	}
	public void unregister(final FileChangesListener listener) {
		listeners.remove(listener);
	}
	public void terminate() {
		stopped = true;
		listeners.clear();
		filesWatchers.clear();
	}
}
